package org.example.es;

import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.client.indices.GetIndexResponse;

import java.io.IOException;

public class ESIndexDemo {
    /**
     * 创建索引
     */
    public static void createIndex() throws IOException {
        new ElasticSearchTask() {
            @Override
            void doSomething(RestHighLevelClient client) throws IOException {
                CreateIndexRequest request = new CreateIndexRequest(userIndex);
                CreateIndexResponse response = client.indices().create(request, RequestOptions.DEFAULT);
                System.out.println("create index： " + response.toString());
            }
        }.execute();
    }

    /**
     * 查询索引
     */
    public static void getIndex() throws IOException {
        new ElasticSearchTask() {
            @Override
            void doSomething(RestHighLevelClient client) throws IOException {
                GetIndexRequest request = new GetIndexRequest(userIndex);
                GetIndexResponse response = client.indices().get(request, RequestOptions.DEFAULT);
                System.out.println("get index aliases :" + response.getAliases());
                System.out.println("get index mappings :" + response.getMappings());
                System.out.println("get index settubgs :" + response.getSettings());
            }
        }.execute();
    }

    /**
     * 删除索引
     */
    public static void deleteIndex() throws IOException {
        new ElasticSearchTask() {
            @Override
            void doSomething(RestHighLevelClient client) throws IOException {
                DeleteIndexRequest request = new DeleteIndexRequest(userIndex);
                AcknowledgedResponse response = client.indices().delete(request, RequestOptions.DEFAULT);
                System.out.println("操作结果:" + response.isAcknowledged());
            }
        }.execute();
    }
}
